<template>
    <view class="goodsBox" v-if="list.length>0">
		<u-loading-page :loading="loadstatus"></u-loading-page>
        <view class="goodsList" v-for="item in list" :key="item.id">
            <view class="Pic">
                <image mode="aspectFill" class="goodsImage" :src="item.cover_thumb"  @tap="$tools.goJump('/pages/goods/view',{id:item.goods_id})"/>
                <!-- 特价限购商品标识 -->
                <view class="PromoteIcon" v-if="tags(item.tag_names,'特惠')">特惠</view>
                <view class="totalStockCount" v-if="item.stock_num==0">{{$t('soldout')}}</view>
            </view>
            <view class="goodsInfo u-flex-m">
                <view class="goodsTop">
					<view class="goodsName moreText" @tap="$tools.goJump('/pages/goods/view',{id:item.goods_id})">{{item.name}}</view>
					<view class="PromoteText u-m-l-10" v-if="tags(item.tag_names,'热卖')"><view class="word">热销</view></view>
				</view>

				<view class="goodsDescription" v-if="item.title!=''||item.title!=null">{{item.title}}</view>
		
                <!-- 特价限购商品标识 -->
                
                <view class="goodsData">
                    <view class="monthlySales" v-if="item.sales_totalnum>0">
                        <text>{{item.sales_totalnum || '0'}}</text><text>{{$t('x_personpaid')}}</text>
                    </view>
					<view class="totalStockCount u-flex-6" v-if="item.stock_num>0">
							<text>{{$t('stock')}}:</text><text>{{item.stock_num}}</text>
					</view>
                </view>

                <view class="bottomOperation">
					<view class="memberPrice">
						<view class="left">{{$t('price')}}</view>
						<view class="right">
							<view class="Price">{{siteInfo.money.symbol}}{{item.price}}</view>
						</view>
					</view>
                    <view class="rightButton">

						<view class="btn-group" v-if="item.sku_id==''||item.sku_id==null">
<button class="spce_btn"
 :loading="loadstatus" loadingText="wait.."
@tap="onPopupButton(parseInt(item.goods_id),parseInt(item.category_id))" :style="[{background:PrimaryColor}]">
{{$t('spce')}}
</button>
							<view class="dot" v-show="goodCartNum(item.goods_id)">{{ goodCartNum(item.goods_id) }}</view>
						</view>
						<view class="btn-group" v-else>
							<button type="default" v-show="goodCartNum(item.goods_id)" plain class="btn reduce_btn"
							 size="mini" hover-class="none" @tap="handleReduce_Cart(parseInt(item.goods_id))">
								<u-icon name="minus" labelPos="bottom"></u-icon>
							</button>
							<view class="number" v-show="goodCartNum(item.goods_id)">{{ goodCartNum(item.goods_id) }}</view>
							<button type="primary" class="btn add_btn" size="min" hover-class="none" :style="[{background:'#666666'}]"
								v-if="(goodCartNum(item.goods_id)>0&&item.goods_type==1)||item.stock_num==0">
								<u-icon name="plus" labelPos="bottom" color="color['u-bg-color']"></u-icon>
							</button>
							<button type="primary" v-else class="btn add_btn" size="min" hover-class="none" 
								@tap="handleAddToCart(JSON.stringify(item),1)" :style="[{background:PrimaryColor}]">
								<u-icon name="plus" labelPos="bottom" color="color['u-bg-color']"></u-icon>
							</button>
						</view>
						
                    </view>
                </view>
            </view>
        </view>

    </view>
</template>

<script>
	import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
	import { api_goods_item } from '@/config/api.js';
	import { isNumber } from 'util';
	export default {
		props:{
			list: {
				type: Array,
				default(){
					return {}
				}
			},
			cart: {
				type: Array,
				default(){
					return []
				}
			}
		},
		computed:{
		    ...mapState(['PrimaryColor','siteInfo']),
			tags() { //计算购物车总数
				return (tags,keytxt) => {
						let goods_tag=tags.split(",")
						let res = false
						goods_tag.forEach((tag,index) => {
							if (tag==keytxt){
								res=true
							}
						})
						return res
					}
			},
			goodCartNum() {	//计算单个商品添加到购物车的数量
				return (id) => {
					if (!this.cart || this.cart.length === 0) {
						return 0;
					}else{
						return this.cart.reduce((acc, cur) => {
							if(cur.id === id) {
								return acc += cur.num
							}
							return acc;
						}, 0);
					}
				}
			},
		},
        data() {
        	return {
				goodsinfo:[],
				loadstatus:false,
				loadstxt:'loading...',
        	};
        },
        methods:{
			handleReduce_Cart(goods_id) {
				const index = this.cart.findIndex(item => item.id === goods_id)
				if (index> -1){
					this.cart[index].num -= 1
					if(this.cart[index].num <= 0) {
						this.cart.splice(index, 1)
					}
				}
				this.$emit('onSyncCart',this.cart)
			},
			handleAddToCart(goods, num) {	//添加到购物车
	
				let cart = this.cart
				goods=JSON.parse(goods)
				const cart_count = Object.keys(this.cart).length
				if (cart_count==0){cart=[]}
				let index=0
				if (cart_count>0){
					index = cart.findIndex(item => {
						if(goods.sku_id>0) {
							return (item.id === parseFloat(goods.goods_id)) && (item.sku_id === goods.sku_id)
						} else {
							return item.id === parseFloat(goods.goods_id)
						}
					})
				}
					
					if(index > -1&&cart_count!=0) {
						if (goods.goods_type==1){
							this.$tools.msg('非实物商口，只需下单一件。')
							num=0 //如果是虚拟物品，不可以往上加
						}
						cart[index].num += num
					} else {

						if (goods.stock_num == 0 || goods.stock_num ==null) {
							uni.$u.toast('库存不足')
							return false;
						}
						if(parseFloat(goods.price)>0){}else{
							this.$tools.msg('价格错误，暂无法购买')
							return false;
						}

						let group_id
						let group_name
						
				// if (this.siteInfo.site.order_group=='brand'){
				// 	group_id = goods.brand_id
				// 	group_name = goods.brand_name
				// }else if(this.siteInfo.site.order_group=='shop'){
				//   if (this.shop_id==''){
				// 	  this.$tools.msg('设置为店铺分组模式但确少shopid,无法下单。');return false;
				//   }
				//   group_id = this.shop_id
				//   group_name = ''
				// }else{
					
				// }
						cart.push({
							id: parseFloat(goods.goods_id),
							goods_id: goods.goods_id,
							goods_name: goods.name,
							group_id:'',
							group_name:'',
							cover_url: goods.cover_url,
							price: goods.price,
							num: num,
							sku_id: goods.sku_id,
							sku_name:goods.sku_name,
							category_id:goods.category_id,
							goods_type:goods.goods_type
						})
					}
					console.log('cart___',cart)
					this.$emit('onSyncCart',cart)
				},


            //打开规格--多规格/多属性
            onPopupButton(goods_id,category_id){
				this.loadstatus=true
				api_goods_item({
					goods_id:goods_id
				},{custom: {load:false}}).then((res) => {
					console.log(res)
					if (res.sku_arr.list.length>0){
						res.sku_arr.initialSku = {}
						res.sku_arr.initialSku['selectedNum'] = 1
						res.category_id=category_id
						for (let [k, v] of Object.entries(res.sku_arr.tree)) {
							res.sku_arr.initialSku[v.k_s] = ''
						}
					}
					this.loadstatus=false
					this.$emit('onOpenPopup',res)
				}).catch((err) =>{})
            },

            
        }
	}
</script>

<style lang="scss" scoped>
	@import '~@/pages/goods/module/shop.scss';

	

</style>
